//
//  WebViewController.m
//  KidReading
//
//  Created by linziyuan on 16/4/13.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "WebViewController.h"
#import "ConstDefine.h"

@interface WebViewController ()<UIWebViewDelegate,MoreBubbleViewController_Delegate>

@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) UIActivityIndicatorView *indicator;
@property (nonatomic, strong) UIImageView *bgView;
@property (nonatomic, strong) UILabel *titleLabel;
//quiz right label
@property (nonatomic, strong) UILabel *quizRLabel;
@end

#define NONETAG      999
#define SHAREBTNTAG  1001
#define BUBBLEBTNTAG 1002
#define DEFUALTSHARE 1003


@implementation WebViewController
{
    BOOL _isPhone;
    NSDictionary *_titleBarDic;
    NSString *_shareUrl;
    NSArray *_bubbleItems;
    UIImageView *bView;
    //
    ZYLoadingProgress* loadingView;
    //
}
static WebViewController* currentWebVC = nil;
+ (instancetype)currentWebVCInstance
{
    return currentWebVC;
}

-(void)hurdleShareSuccessReflshWebView{
    NSString * strJS = @"finishCallback()";
    [_webView stringByEvaluatingJavaScriptFromString:strJS];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.contentView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.edges.JRMAS_equalTo(0);
    }];
    //
    currentWebVC = self;
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        _isPhone = YES;
    }else {
        _isPhone = NO;
    }
    bView = [[UIImageView alloc] init];
    [self.contentView addSubview:bView];
    [bView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.edges.equalTo(self.contentView);
    }];
    bView.backgroundColor = [UIColor colorWithHexString:@"#EDEEF4"];
    [self setUpNavibar];
    [self initialUI];
    [self loadRequest];
    //self.title = [NSString stringWithFormat:@"WebView_%@", self.url];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.contentView bringSubviewToFront:self.naviBar];
    [self forceToOrientation:UIInterfaceOrientationPortrait];
    currentWebVC = self;
    [[RootViewController shareLastInstance] stopAudioPlay:NO];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.countActivity.hidden = YES;
}

- (void)setUpNavibar {
    CGFloat btnWidth = 48/ratio_w;
    CGFloat logoWidth = self.contentView.frame.size.width*0.7;
    CGFloat logoHeight = 25.0;
    CGFloat labelfont = 24.0;
    CGFloat loadingHeight = 3;
    CGFloat loadingBpod = 7;
    CGFloat labelW = 80.0;
    CGFloat quizLabelFont = 20.0/ratio_h;
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        //btnWidth = 24.0;
        //logoWidth = 300.0;
        logoHeight = 20.0;
        labelfont = 18.0;
        loadingHeight = 2;
        loadingBpod = 6;
        labelW = 50.0;
    }
   
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, logoWidth, logoHeight)];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.text = self.barTitle;
    self.titleLabel.font = [UIFont systemFontOfSize:labelfont];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    self.rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightBtn.frame = CGRectMake(0, 0, btnWidth, btnWidth);
    [self.rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.rightBtn addTouchScaleTransitions];
    
    //quiz right label
    self.quizRLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, labelW, btnWidth)];
    self.quizRLabel.textColor = [UIColor whiteColor];
    self.quizRLabel.textAlignment = NSTextAlignmentRight;
    self.quizRLabel.font = [UIFont systemFontOfSize:quizLabelFont];
    NSArray *rightViews = @[self.rightBtn];
    if (self.showType == SettingShowType_Quiz) {
        rightViews = @[self.quizRLabel];
    }
    
    self.naviBar = [JRNaviBar getJRNaviBarWithSuperView:self.contentView centerView:self.titleLabel leftViews:nil rightViews:rightViews leftSpace:20/ratio_w rightSpace:25/ratio_w];
    [self.contentView addSubview:self.naviBar];
    //
    loadingView = [ZYLoadingProgress new];
    loadingView.colorMove = NO;
    loadingView.colors = @[[[UIColor whiteColor] colorWithAlphaComponent:0.1],[UIColor whiteColor],[UIColor whiteColor]];
    [self.naviBar addSubview:loadingView];
    CGFloat nh = self.naviBar.height-loadingBpod;
    [loadingView JRMAS_remakeConstraints:^(JRMASConstraintMaker *make) {
        make.left.right.equalTo(self.contentView);
        make.height.equalTo(@(loadingHeight));
        make.top.JRMAS_equalTo(nh);
    }];
    //
    [self addBackView];
}


- (void)refreshbar {
    NSString *imgStr = @"detail_btn_share_norma.png";
    self.rightBtn.tag = DEFUALTSHARE;
    if (_titleBarDic) {
        NSString *model = [_titleBarDic valueForKey:@"model"];
        if ([model isEqualToString:@"bubble"]) {
            imgStr = @"more_btn_menu_normal.png";
            self.rightBtn.tag = BUBBLEBTNTAG;
            _bubbleItems = [_titleBarDic valueForKey:@"value"];
        }
        else if ([model isEqualToString:@"share"]) {
            imgStr = @"detail_btn_share_norma.png";
            self.rightBtn.tag = SHAREBTNTAG;
            NSString *value = [_titleBarDic valueForKey:@"value"];
            _shareUrl = value;
        } else if ([model isEqualToString:@"none"]) {
            imgStr = @"";
            self.rightBtn.tag = NONETAG;
        }
        //
    }
    [self.rightBtn setBackgroundImage:[UIImage imageNamed:imgStr] forState:UIControlStateNormal];
    [self.rightBtn setBackgroundImage:[UIImage imageNamed:imgStr] forState:UIControlStateHighlighted];
}

- (void)initialUI {
    
    self.bgView = [[UIImageView alloc] init];
    self.bgView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:self.bgView];
    [self.bgView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.top.equalTo(self.naviBar.JRMAS_bottom);
        make.left.right.bottom.equalTo(self.contentView);
    }];
    self.webView = [self getAnWebView];
//
//    self.indicator = [[UIActivityIndicatorView alloc] init];
//    self.indicator.translatesAutoresizingMaskIntoConstraints = NO;
//    [self.contentView addSubview:self.indicator];
//    self.indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
//    [self.indicator lyt_setSize:CGSizeMake(30, 30)];
//    [self.indicator lyt_centerXInParentWithOffset:0];
//    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
//       [self.indicator lyt_centerYInParentWithOffset:-10];
//    }else {
//      [self.indicator lyt_centerYInParentWithOffset:-70];
//    }
}

- (UIWebView *)exchangeWebView
{
    UIWebView* wbview = [self getAnWebView];
    [self.webView.superview insertSubview:wbview belowSubview:self.webView];
    [self.webView stopLoading];
    [self.webView removeFromSuperview];
    self.webView = wbview;
    //
    return wbview;
}

- (UIWebView *)getAnWebView {
    CGFloat hpadding = 20.0;
    CGFloat pPadding = 30.0;
    if (_isPhone) {
        hpadding = 15.0;
        pPadding = 20.0;
    }
    if (self.isfullScrean) {
        hpadding = 0;
        pPadding = -3;
        if (_isPhone) {
            pPadding = -3.0;
        }
    }
    UIWebView *webV = [[UIWebView alloc] init];
    webV.mediaPlaybackRequiresUserAction = NO;
    webV.allowsInlineMediaPlayback = YES;
    webV.delegate = self;
    [self.contentView addSubview:webV];
    [webV JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.top.equalTo(self.naviBar.JRMAS_bottom).offset(pPadding);
        make.left.equalTo(self.contentView).offset(pPadding);
        make.right.equalTo(self.contentView).offset(-pPadding);
        make.bottom.equalTo(self.contentView).offset(-hpadding);
    }];
    
    webV.backgroundColor = [UIColor clearColor];
    //self.webView.paginationMode = UIWebPaginationModeTopToBottom;
    webV.scrollView.showsVerticalScrollIndicator = NO;
    webV.scrollView.showsHorizontalScrollIndicator = NO;
    
    if (self.clear_Bg) {
        [webV setOpaque:NO];
        webV.backgroundColor = [UIColor clearColor];
        webV.paginationMode = UIWebPaginationModeUnpaginated;
        webV.backgroundColor = [UIColor clearColor];
    }else{
        [webV setOpaque:YES];
        webV.backgroundColor = [UIColor clearColor];
        //self.webView .paginationMode = UIWebPaginationModeTopToBottom;//从上而下
        webV.backgroundColor = [UIColor whiteColor];
    }
    return webV;
}

- (void)loadRequest{
    if (self.showType == SettingShowType_Local) {
        self.titleLabel.text = NSLocalizedString(@"canNotLinkNet", nil);
        NSString *filePath = [[NSBundle mainBundle]pathForResource:[DataProcessing chooseLanguageFromCN:@"localFiles.bundle/network_available_cn" andEN:@"localFiles.bundle/network_available_en"] ofType:@"html"];
        NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        [self.webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];
    }
    if (self.url) {
        if (self.showType == SettingShowType_H5) {
            NSString *url = [NetRequest netFullUrl_Get:self.url fromDict:[[NetRequestWithCache_JR shareSingle] netRequestAddBaseInfo:self.otherParas]];
#ifdef __Debug_JSLog
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
#else
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
#endif
            [self.webView loadRequest:request];
        }
        else if (self.showType == SettingShowType_contact || self.showType == SettingShowType_normalLink) {
#ifdef __Debug_JSLog
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
#else
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
#endif
            [self.webView loadRequest:request];
        }
        else if (self.showType == SettingShowType_Quiz) {
            
#ifdef __Debug_JSLog
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
#else
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
#endif
            [self.webView loadRequest:request];
        }
        else {
            [[NetRequest shareSingle] webViewAskNet:self.url andBaseUrl:__Ser3_0_URL_Base_ parameters:@{} success:^(NSData *retData) {
                if (retData) {
                    [self.webView loadData:retData MIMEType:@"text/html"  textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:self.url]];
                }else {
                    [self showEmptyViewWithType:EmptyShowType_Web tapEnabel:YES];
                }
            } failure:^(NSError *error) {
                [self showEmptyViewWithType:EmptyShowType_Web tapEnabel:YES];
                //[self showEmptyForWeb];
            }];
        }
    }
}


#pragma mark Acitons

- (void)showEmptyViewWithType:(EmptyShowType)type tapEnabel:(BOOL)tapenable{
    self.bgView.hidden = YES;
    bView.hidden = YES;
    [self.emptyShow emptyShowWithType:type tapEnabel:tapenable hideView:self.webView defineStr:nil];
}

- (void)tapEmptyShow {
    self.bgView.hidden = NO;
    bView.hidden = NO;
    [self loadRequest];
    [self.emptyShow dismissEmptyShowView:self.webView];
}

- (void)clickBack {
    if (_popUpType == WebPopUpType_Push) {
        [self.navigationController popViewControllerAnimated:YES];
    }else if (_popUpType == WebPopUpType_Present){
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)rightBtnClick:(UIButton *)btn {
    if (btn.tag == BUBBLEBTNTAG) {
        NSMutableArray *titles = [NSMutableArray array];
        for (NSDictionary *bitem in _bubbleItems) {
            NSString *nameEn = [bitem valueForKey:@"nameEn"];
            NSString *nameCh = [bitem valueForKey:@"nameZh"];
            NSString *title = [DataProcessing chooseLanguageFromCN:nameCh andEN:nameEn];
            [titles addObject:title];
        }
        //isCurrent = 1
        MoreBubbleViewController* bubbleVC = [[MoreBubbleViewController alloc] init];
        bubbleVC.followView = self.rightBtn;
        // bubbleVC.currentOrderType = _orderby;
        bubbleVC.delegate = self;
        bubbleVC.orderByArr = _bubbleItems;
        [bubbleVC showBubbleViewSelfDefineToVC:self];
    }else if (btn.tag == SHAREBTNTAG) {
        if (_shareUrl.length>0) {
            [self shareWithUrl:_shareUrl];
        }
    }else if(btn.tag == DEFUALTSHARE){
        [self shareWithUrl:self.webView.request.URL.absoluteString];
    }
}

- (void)moreBubbleViewController_select:(MoreBooksOrderType)odertype {
    //NSLog(@"tag ------ %ld",(unsigned long)odertype);
    NSDictionary *currentDic = _bubbleItems[(odertype-1)];
    NSString *url = [currentDic valueForKey:@"url"];
    if (url.length > 0) {
        UIWebView* webv = [self exchangeWebView];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
        [webv loadRequest:request];
    }
}

- (void)shareWithUrl:(NSString *)url {
    /*
     desc = "\U53c2\U52a0\U4e86WaWaYaYa\U7231\U8bfb\U7684\U7ed8\U672c\U521b\U4f5c\U5927\U8d5b\Uff0c\U5feb\U6765\U7ed9TA\U6295\U7968\U5427\Uff01";
     img = "http://aidu.wawayaya.com/Files/BookImages/41460/zbxy130114-953460e5-2d1c-47ea-862e-b98f85a256db-0.jpg?stamp=1456631511719";
     model = share;
     title = "\U7684\U7ed8\U672c\U4f5c\U54c1";
     value = "http://10.135.195.150:9797/apiweb/bookarticle/getBookArticleShare?bookId=1157&activityId=1&userId=10990";
     */
    NSString *shareImg = [_titleBarDic valueForKey:@"img"];
    NSString *shareTitle = [_titleBarDic valueForKey:@"title"];
    NSString *shareDes = [_titleBarDic valueForKey:@"desc"];
    
    NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];
    NSArray *iconArr = [infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"];
    NSString *icon = [iconArr lastObject];
    if ([DataProcessing iOS7_low]) {
        if (iconArr.count>1) {
            icon = iconArr[1];
        }
        
    }
    UIImage *imgicon = [UIImage imageNamed:icon];
    id img = imgicon;
    if (shareImg.length > 0) {
        img = shareImg;
    }
    NSString *title = NSLocalizedString(@"sharetitle", nil);
    if (shareTitle.length>0) {
        title = shareTitle;
    }
    NSString *text = NSLocalizedString(@"sharetext", nil);
    if (shareDes.length > 0) {
        text = shareDes;
    }
    
    NSArray* imageArray = @[img];
    if (imageArray) {
        [[ShareManager shareManager] JRShareWithText:text ImageArray:imageArray Url:[NSURL URLWithString:url] Title:title Type:SSDKContentTypeAuto BaseView:self.rightBtn statusChange:^(SSDKResponseState state, SSDKPlatformType type) {
            if (state == SSDKResponseStateBegin) {
                [[WaWaYaYaRewardManager defaultManager] logRewardEventIsNeedHandle:YES ActCode:ActCode_WebShareSuccess Param:nil];
            }
        }];
    }
}

- (void)tapBack {
    
    [JSDataProcessing cancelAllLocalActions];
    if (self.showType == SettingShowType_Quiz) {
        [[DBHelper shareInstance] readInfo_Dicts_sendToNet];
        if (_popUpType == WebPopUpType_Push) {
            [self.navigationController popViewControllerAnimated:YES];
        }else if (_popUpType == WebPopUpType_Present){
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        if (currentWebVC == self) {
            currentWebVC = nil;
        }
    }
    [self.webView stopLoading];
    if (self.webView.canGoBack) {
       [self.webView goBack];
    }else {
        if (_popUpType == WebPopUpType_Push) {
            [self.navigationController popViewControllerAnimated:YES];
        }else if (_popUpType == WebPopUpType_Present){
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        if (currentWebVC == self) {
            currentWebVC = nil;
        }
    }
}
#pragma mark WebView Delegate

- (void)webViewDidStartLoad:(UIWebView *)webView {
    [loadingView startAnimating];
    if (self.showType == SettingShowType_H5 || self.showType == SettingShowType_normalLink) {
        self.titleLabel.text = @"Loading...";
        self.rightBtn.hidden = YES;
    }
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (self.showType == SettingShowType_Quiz) {
        NSString* url = request.URL.absoluteString;
        NSArray* arr = [url componentsSeparatedByString:@"?"];
        NSString* urlbase = arr.firstObject;
        if ([urlbase hasSuffix:@"/quizdata.html"] && arr.count == 2) {
            NSString* str = arr[1];
            NSDictionary* refDict = [self dicTogetRef:str];
            str = refDict[@"data"];
            str = [str URLDecodedString];
            NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
            NSError* error = nil;
            NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            if (dict) {
                [[DBHelper shareInstance] addQuizInfoWithQuizDict:dict];
            }
        }
        NSString *titleStr = [JSDataProcessing quizTitleWithUrl:url];
        if (titleStr.length) {
            titleStr = [titleStr URLDecodedString];
            self.titleLabel.text = titleStr;
        }
        NSString *rightStr = [JSDataProcessing quizRightTitleWithUrl:url];
        //if (rightStr.length) {
            rightStr = [rightStr URLDecodedString];
            self.quizRLabel.text = rightStr;
        //}
        [JSDataProcessing startURL:request.URL.absoluteString webView:self.webView currentVC:self];
        if ([request.URL.absoluteString hasPrefix:@"localcall::"]) {
            return NO;
        }
    }
    if (webView.newWebView) {
        webView = [self exchangeWebView];
        [webView loadRequest:request];
        return NO;
    }else {
        //[self.indicator startAnimating];
        if(self.isClickToBrower && navigationType == UIWebViewNavigationTypeLinkClicked){
            [[UIApplication sharedApplication] openURL:request.URL];
            return NO;
        }
        [JSDataProcessing startURL:request.URL.absoluteString webView:self.webView currentVC:self];
        if ([request.URL.absoluteString hasPrefix:@"localcall::"]) {
            return NO;
        }
    }
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [loadingView stopAnimating];
    //[self.indicator stopAnimating];
    //[self.emptyShow dismissEmptyShowView:self.webView];
    if (self.claar_DeviceWith) {
        [JSDataProcessing reg_poptool_js:self.webView];
        [JSDataProcessing js_poptool_clean_device_width:self.webView];
    }
    
    if (self.showType == SettingShowType_H5 || self.showType == SettingShowType_normalLink) {
        
        if (self.showType == SettingShowType_H5) {
            _titleBarDic = [JSDataProcessing titleBarRightInfo:webView];
            self.rightBtn.hidden = NO;
            [self refreshbar];
        }
        self.titleLabel.text = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
        //[self logJS];
    }
    [JSDataProcessing setUinfoCallback:webView];
}
//
-(void)presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_USEC), dispatch_get_main_queue(),
                   ^
                   { [super presentViewController:viewControllerToPresent animated:flag completion:completion]; }
                   );
}
//
- (void)logJS {
    NSString *lJs = @"document.documentElement.innerHTML";
    NSString *lHtml = [self.webView stringByEvaluatingJavaScriptFromString:lJs];
    NSLog(@"%@",lHtml);
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    //[self showEmptyViewWithType:EmptyShowType_Defualt];
    [loadingView stopAnimating];
    //[self.indicator stopAnimating];
    if (self.showType == SettingShowType_H5) {
        //NSLog(@"self's url ------%@,webview's url -------%@",self.url,webView.request.URL.absoluteString);
        _titleBarDic = [JSDataProcessing titleBarRightInfo:webView];
        if (error.code != 101 ) {
            self.titleLabel.text = @"";
        }
        [self refreshbar];
        if (error.code != 101 && error.code != (-999)) {    //101 can't be shown
            if (self.url.length>0) {
                [self showEmptyViewWithType:EmptyShowType_Web tapEnabel:YES];
            }else {
                [self showEmptyViewWithType:EmptyShowType_Defualt tapEnabel:NO];
            }
        }
    }else if (self.showType == SettingShowType_normalLink) {
        if (error.code != 101 ) {
            self.titleLabel.text = @"";
        }
    }
}

- (NSDictionary*)dicTogetRef:(NSString*)refStr
{
    if (refStr) {
        NSMutableDictionary* mdic = [NSMutableDictionary new];
        NSArray* arr = [refStr componentsSeparatedByString:@"&"];
        for (NSString* str in arr) {
            NSArray* kvs = [str componentsSeparatedByString:@"="];
            if (kvs.count == 2) {
                [mdic setObject:kvs[1] forKey:kvs[0]];
            }
        }
        return mdic;
    }
    return nil;
}

#pragma mark Helper

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
